/*
 * @Description: 辅助
 * @Author: HuiSir<273250950@qq.com>
 * @Date: 2021-12-31 10:19:03
 * @LastEditTime: 2025-09-03 14:55:34
 */
import { Router, RouteRecordRaw } from "vue-router";
import { PermTypeOpt, MenuTypeOpt } from "@/helpers/selection";
import { project } from "@/init/config";
import { fieldMapping } from "@/utils/common";
import useCommonStore from "./modules/common";

/**
 * views目录所有文件列表
 * vite编译内置方法import.meta.glob
 */
export const viewModules = import.meta.glob("../views/**/*.vue");

/**
 * 树结构权限递归导入路由,若不是树结构则不会递归
 * 这里不管是不是树结构都适用
 * 这里顺便将菜单和功能权限提取出来（解tree）
 * tree => push dynamicRoutes
 */
export const usePermTreeHandler = (
  permTreeList: Permission[],
  router: Router
) => {
  // 动态路由name缓存
  const dynamicRoutes: string[] = [];
  // 功能权限缓存
  const funcPermCodes: string[] = [];
  // 菜单缓存（非树）
  const menus: Permission[] = [];

  (function Recursion(perms: Permission[]) {
    // 动态添加路由
    // 重新登录后这里无需考虑路由会重复。相同name的路由会覆盖先前路由
    for (let index = 0; index < perms.length; index++) {
      const perm = perms[index];

      // 字段映射
      fieldMapping({
        data: perm,
        fieldsMap: project.permissionFields,
      });

      const { type, viewPath } = perm;

      // 功能
      if (type === PermTypeOpt.func) {
        funcPermCodes.push(perm.code);
      }

      // 菜单
      if (type === PermTypeOpt.menu) {
        menus.push(perm);
      }

      // 动态路由
      if (viewPath) {
        const Route = menu2Route(perm as Permission);

        router.addRoute("Home", Route);
        // 缓存动态路由name表（父级）
        if (Route.name) {
          dynamicRoutes.push(Route.name as string);
        }
      }

      // 不管是不是树结构都适用
      if (perm.children?.length) {
        Recursion(perm.children as Permission[]);
      }
    }
  })(permTreeList);

  // menus排序-从小到大
  menus.sort((a1, a2) => a1.orderRank - a2.orderRank);

  return {
    dynamicRoutes,
    funcPermCodes,
    menus,
  };
};

// 菜单点击
export const menuJump = async (menu: Permission, router: Router) => {
  switch (menu.menuType) {
    case MenuTypeOpt.category:
      return;
      break;
    case MenuTypeOpt.route:
      // 路由
      if (menu.blank) {
        const routerResolve = router.resolve({
          name: menu.code,
        });
        window.open(routerResolve.href, "_blank");
      } else {
        router.push({ name: menu.code });
      }
      break;
    case MenuTypeOpt.link:
      // 链接
      if (menu.blank && menu.path) {
        window.open(menu.path);
      } else {
        router.push({ name: "Frame", params: { id: menu.id } });
      }
      break;
    case MenuTypeOpt.button:
      // 按钮
      if (menu.triggerMethod) {
        // eslint-disable-next-line
        await (useCommonStore() as any)[menu.triggerMethod]();
      }
      break;
  }
};

/**
 * menuItem => routeItem
 */
function menu2Route(perm: Permission): RouteRecordRaw {
  const { path, title, code, icon, keepAlive, internal, viewPath, blank } =
    perm;
  return {
    path: path as string,
    name: code,
    component: viewModules[`../${viewPath}`],
    meta: { title, code, icon, keepAlive, internal, blank } as RouteMeta,
  };
}
